package com.ys.day31.p3FastJson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 描述: json 远程下载工具类
 *
 * @author CodeYang
 * @version 2021/1/18 13:01
 */
public class JSONUtils {

    /**
     *将远程服务器的JSON数据下载到本地
     *      * 1 创建URL对象
     *      * 2 向远程服务器发起请求连接
     *      * 3 设置超时时间
     *      * 4 获取服务器的响应码
     *      * 5 打开远程服务器的输入流，读取JSON数据
     *      * 6 返回读取结果
     * @param urlPath
     * @return
     * @throws Exception
     */
    public  static String  downJsonData(String urlPath) throws  Exception {
        // 1
        URL url = new URL(urlPath);
        // 2发起 HTTP 原生请求
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        // 设置超时
        httpConnection.setConnectTimeout(2000);
        // 4获取 服务响应码
        int responseCode = httpConnection.getResponseCode();

        //5 判断是否请求成功
        if (200!=responseCode ){
            // 请求失败
            return null;
        }
        // 成功 就做json 字符 写入缓冲流,并返回成一个str (json 的本质就是一个str)
        try(
                InputStream inputStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        )
         {
            String line =null;
            StringBuilder sb = new StringBuilder(30);
            while ((line=reader.readLine())!=null){
                sb.append(line);
            }

             return sb.toString();
         }


    }

}
